package cn.wyd.shield.web;


import cn.wyd.shield.dto.resp.Message;
import cn.wyd.shield.dto.resp.UserLoginMessage;
import cn.wyd.shield.exception.auth.AuthCertException;
import cn.wyd.shield.token.jwt.JwtToken;
import cn.wyd.shield.token.jwt.JwtUtil;
import cn.wyd.shield.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


@RestController
public class UserLoginController {

    @GetMapping("/login")
    public Message doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            String name = req.getParameter("name");
            String pwd  = req.getParameter("pwd");
            if(StringUtil.isBlank(name)){
                throw new AuthCertException("用户名为空");
            }
            if(StringUtil.isBlank(pwd)){
                throw new AuthCertException("密码为空");
            }
            JwtToken jwtToken = new JwtToken("1",name);
            String str = JwtUtil.build(jwtToken.toPlayLoadString(),JwtUtil.secret);
            UserLoginMessage userLoginMessage = new UserLoginMessage("SUCCESS","获取token成功",str);
            return userLoginMessage;
        }catch (AuthCertException e){
            Message message = new Message("ERROR_CERT", e.getMessage());
            return message;
        } catch (NoSuchAlgorithmException e) {
            Message message = new Message("ERROR_Algorith", e.getMessage());
            return message;
        } catch (InvalidKeyException e) {
            Message message = new Message("ERROR_Algorith", e.getMessage());
            return message;
        }catch (Exception e) {
            Message message = new Message("ERROR_CASE", e.getMessage());
            return message;
        }
    }
}
